package utils

import (
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/sms/bytes"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
)

var BUCKET = "qiniuyundemo-go"
var ACCESSKEY = "x0abHv3YMHSK_Gii2KM9CVPIC25EYg__LrkBId5c"
var SECRETKEY = "oNXf-Ibo7E341Zz2QXfWBrlZP0BVTV-Z86fxcqGE"
var DOMAIN = "rp85gtiee.bkt.clouddn.com"

/*获取客户端上传凭证*/
func GetClientToken() string {
	putPolicy := storage.PutPolicy{
		// 设置存储空间名称
		Scope: BUCKET,
		// 设置凭证有效期为2个小时，不设置默认1个小时 --> 3600s
		Expires: 7200,
		// 文件上传到七牛之后，收到的回复内容格式
		ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}`,
	}
	mac := qbox.NewMac(ACCESSKEY, SECRETKEY)
	return putPolicy.UploadToken(mac)
}

/*覆盖上传的凭证*/
func GetOverwriteToken(key string) string {
	putPolicy := storage.PutPolicy{
		Scope:      fmt.Sprintf("%s:%s", BUCKET, key),
		Expires:    7200,
		ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}`,
	}
	mac := qbox.NewMac(ACCESSKEY, SECRETKEY)
	return putPolicy.UploadToken(mac)
}

/*文件上传*/
func Upload(file *multipart.FileHeader) {
	// 对象的key
	key := file.Filename
	// 获取可覆盖的上传凭证
	token := GetOverwriteToken(key)

	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Region = &storage.ZoneHuadongZheJiang2
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = true

	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "github logo",
		},
	}

	fileContent, _ := file.Open()
	byteContainer := make([]byte, 1000000)
	_, _ = fileContent.Read(byteContainer)
	dataLen := int64(len(byteContainer))
	err := formUploader.Put(context.Background(), &ret, token, key, bytes.NewReader(byteContainer), dataLen, &putExtra)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ret.Key, ret.Hash)
}

/*文件下载*/
func DownPublicUrl(key string) string {
	publicAccessURL := storage.MakePublicURL(DOMAIN, key)
	return fmt.Sprintf("http://%s", publicAccessURL)
}
